package services;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Category;
import model.Item;
import model.Member;

import org.json.JSONArray;
import org.json.JSONObject;

import utils.WebUtils;
import core.Lookup;
import core.ManagerLocal;
import core.MemberManagerLocal;

public class GetItem extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		
		process(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		process(req,resp);
	}

	private void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		Integer idItem = WebUtils.safeGetParameterInteger(req, "idItem");
		
		String memberCellphone = WebUtils.safeGetParameterString(req, "memberCellphone");
		String memberEmail = WebUtils.safeGetParameterString(req, "memberEmail");
		String memberPassword = WebUtils.safeGetParameterString(req, "memberPassword");
		
		
		if(idItem == null){
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "idItem parameter is required");
			return;
		}
		
		ManagerLocal manager = Lookup.lookupManager();
		MemberManagerLocal memberManager = Lookup.lookupMemberManager();
		
		Member member = memberManager.loginMember(memberCellphone, memberEmail, memberPassword);
		
		Item item = manager.get(Item.class, idItem);
		
		if(item == null){
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "item not found");
			return;
		}		
		
		if(member == null || (!member.isSuperAdmin() && !member.getIdMember().equals(item.getIdItem()))){
			resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "not authorized");
			return;	
		}
		
		String outputString = toJson(item).toString();
		
		PrintWriter writer = resp.getWriter();
		resp.setContentType("text/html;charset=UTF-8");
		writer.print(outputString);
		writer.close();
	}
	
	private JSONObject toJson(Item item) {
		try{
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("idItem", item.getIdItem());
			jsonObj.put("name", item.getName());
			jsonObj.put("description", item.getDescription());
			
//			if(item.getCategory() != null){
//				jsonObj.put("idCategory", item.getCategory().getIdCategory());
//				jsonObj.put("categoryName", item.getCategory().getName());
//			}
			
			if(item.getCategories() != null){
				JSONArray jsonArray = new JSONArray();
				
				for (Category category : item.getCategories()) {
					JSONObject c = new JSONObject();
					c.put("idCategory", category.getIdCategory());
					c.put("categoryName", category.getName());					
					jsonArray.put(c);
				}
				
				jsonObj.put("categories", jsonArray);				
			}	
			
			if(item.getCategories() != null){
				String categoriesName = "";
				String categoriesId = "";
				for (Category category : item.getCategories()) {
					categoriesName += category.getName() + ", ";
					categoriesId += category.getIdCategory() + ", ";
				}
				int i = categoriesName.lastIndexOf(", ");
				if(i>0){
					categoriesName = categoriesName.substring(0, i);
				}
				i = categoriesId.lastIndexOf(", ");
				if(i>0){
					categoriesId = categoriesId.substring(0, i);
				}			
				jsonObj.put("categoriesName", categoriesName);
				jsonObj.put("categoriesId", categoriesId);				
			}				

			jsonObj.put("latitude", item.getLatitude());
			jsonObj.put("longitude", item.getLongitude());
			jsonObj.put("street", item.getStreet());
			jsonObj.put("state", item.getState());
			jsonObj.put("city", item.getCity());
			jsonObj.put("country", item.getCountry());
			jsonObj.put("zipcode", item.getZipcode());
			
			jsonObj.put("phone", item.getPhone());
			jsonObj.put("cellphone", item.getCellphone());
			jsonObj.put("email", item.getEmail());
			jsonObj.put("skype", item.getSkype());
			jsonObj.put("url", item.getUrl());
			
			return jsonObj;
		}catch (Exception e){
			throw new RuntimeException(e);
		}
	}	
	

	

}
